package com.education.cms.web;

import com.education.cms.common.ResultModle;
import com.education.cms.domain.User;
import com.education.cms.dto.user.LoginDto;
import com.education.cms.dto.user.RegisterDto;
import com.education.cms.dto.user.ShowUserListDto;
import com.education.cms.service.UserService;
import com.education.cms.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    @PostMapping("login")
    public ResultModle login(@RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response){
        User user=userService.login(loginDto.getUsername(), loginDto.getPassword());
        if (user == null){
            return ResultModle.error("用户名或密码错误！");
        }else {
            Cookie cookie = new Cookie(loginDto.getUsername(), loginDto.getPassword());
            response.addCookie(cookie);
            String ticket = UUID.randomUUID().toString().replace("-","");
            request.getSession().setAttribute("loginfo",ticket);
            redisUtils.set(ticket, user.getUserId()+"-"+user.getStatus());
            return ResultModle.ok(user);
        }
    }
    @PostMapping("register")
    public ResultModle register(@RequestBody RegisterDto registerDto){
        return ResultModle.ok(userService.register(registerDto));
    }
    @GetMapping("logout")
    public ResultModle logout(HttpServletRequest request){
        String ticket = (String) request.getSession().getAttribute("loginfo");
        redisUtils.delete(ticket);
        request.getSession().removeAttribute("loginfo");
        return ResultModle.ok();
    }
    /**
     * 查询用户列表（管理员权限
     */
    @PostMapping("userList/{page}")
    public ResultModle showUserList(@PathVariable("page")int page,@RequestBody ShowUserListDto userListDto){
        Pageable pageable = PageRequest.of(page-1,5);
        Page<User> users = userService.showUserList(userListDto,pageable);
        return ResultModle.ok(users);
    }
    /**
     * 修改个人信息
     */
    /*@PostMapping("editMyInfo")
    public ResultModle editMyInfo(@RequestBody )*/
}
